package csdwa;

/**
 * This class handles the pagination functions. Additionally, it is intended to
 * be used in the jsp pages as it keeps track of the first and previous ids as
 * well as the page size.
 *
 * @author Anton Strack
 */
public class Paginator<E extends Post> {

    private int nextId = 0;
    private int previousId = 0;
    private int pageSize;

    public Paginator() {
    }

    public Paginator(int pageSize) {
        this.pageSize = pageSize;
    }

    public CsdwaDao<E> getNext(CsdwaDao<E> dao) {
        dao.setUseRelatedMarkers(true);
        int result = dao.selectNext(this.getNextId(), this.getPageSize());

        if (result > 0) {
            this.setNextId(dao.getBeans().get(0).getId());
            this.setPreviousId(dao.getBeans().get(dao.getBeans().size() - 1).getId());
        } else {
            this.setPreviousId(this.getNextId());
        }
        return dao;
    }

    public CsdwaDao<E> getPrevious(CsdwaDao<E> dao) {

        dao.setUseRelatedMarkers(true);
        int result = dao.selectPrevious(this.getPreviousId(), this.getPageSize());

        if (result > 0) {
            this.setNextId(dao.getBeans().get(0).getId());
            this.setPreviousId(dao.getBeans().get(dao.getBeans().size() - 1).getId());
        } else {
            this.setNextId(this.getPreviousId());
        }
        return dao;
    }

    /**
     * @return the pageSize
     */
    public int getPageSize() {
        return pageSize;
    }

    /**
     * @param pageSize the pageSize to set
     */
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * @return the nextId
     */
    public int getNextId() {
        return nextId;
    }

    /**
     * @param nextId the nextId to set
     */
    public void setNextId(int nextId) {
        this.nextId = nextId;
    }

    /**
     * @return the previousId
     */
    public int getPreviousId() {
        return previousId;
    }

    /**
     * @param previousId the previousId to set
     */
    public void setPreviousId(int previousId) {
        this.previousId = previousId;
    }
}
